<template>
  <div>
    <!-- 条件查询提现表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="订单日期">
          <el-date-picker
            v-model="searchModel.createDate"
            type="daterange"
            :disabledDate="disabledDateFn"
            @calendar-change="calendar"
            @visible-change="curDate = null"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :clearable="false"
            placeholder="选择日期范围最多3个月"
          />
        </el-form-item>
        <el-form-item label="审核日期">
          <el-date-picker
            v-model="searchModel.checkTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="提现日期">
          <el-date-picker
            v-model="searchModel.withdrawTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="交易订单号">
          <el-input
            v-model.trim="searchModel.dealNo"
            placeholder="请输入交易订单号"
          />
        </el-form-item>
        <el-form-item label="订单号">
          <el-input
            v-model.trim="searchModel.orderNo"
            placeholder="请输入订单号"
          />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input
            v-model.trim="searchModel.userId"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
            placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchModel.state" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option label="处理中" value="0" />
            <el-option label="提现成功" value="1" />
            <el-option label="提现失败" value="2" />
            <el-option label="审核中" value="3" />
            <el-option label="审核通过" value="4" />
            <el-option label="审核不通过" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道">
          <!-- <el-input v-model="searchModel.payType" disabled placeholder="易宝" /> -->
          <el-select v-model="searchModel.withdrawType" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option label="易宝" value="易宝" />
            <el-option label="富友" value="富友" />
            <el-option label="新生" value="新生" />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐系列">
          <el-input
            v-model.trim="searchModel.packSeriesName"
            placeholder="请输入套餐系列"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#ea5b24" @click="searchOrder()"
            >查询</el-button
          >
          <el-button
            type="primary"
            color="#ea5b24"
            @click="exportOrder()"
            v-if="pinia.isShow[88]"
            >导出Excel</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 汇总数据 -->
    <div class="div-summaryData">
      <span class="text-summaryData"
        >提现成功总金额：{{
          summaryData.successAmt ? summaryData.successAmt.toFixed(2) : "0.00"
        }}</span
      >
      <span class="text-summaryData"
        >提现审核中总金额：{{
          summaryData.checkAmt ? summaryData.checkAmt.toFixed(2) : "0.00"
        }}</span
      >
      <span class="text-summaryData"
        >提现处理中总金额：{{
          summaryData.handleAmt ? summaryData.handleAmt.toFixed(2) : "0.00"
        }}</span
      >
      <span class="text-summaryData"
        >提现失败总金额：{{
          summaryData.failAmt ? summaryData.failAmt.toFixed(2) : "0.00"
        }}</span
      >
    </div>
    <!-- 提现列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column prop="createTime" width="160" label="订单日期" />
        <el-table-column prop="withdrawType" label="提现渠道" />
        <el-table-column prop="packSeriesName" width="100" label="系列名称" />
        <el-table-column prop="orderNo" width="160" label="订单号" />
        <el-table-column prop="dealNo" width="160" label="交易订单号" />
        <el-table-column prop="checkTime" width="160" label="审核日期" />
        <el-table-column prop="withdrawTime" width="160" label="提现日期" />
        <el-table-column prop="userId" label="用户ID" />
        <el-table-column prop="price" label="提现金额" />
        <el-table-column prop="bankNo" width="110" label="收款银行账户" />
        <el-table-column prop="accountName" width="120" label="银行户名" />
        <el-table-column prop="initialPrice" width="100" label="初始手续费" />
        <el-table-column prop="rate" label="额外费率" />
        <el-table-column
          prop="receivedPrice"
          width="110"
          label="实际到账金额"
        />
        <el-table-column
          prop="totalCommission"
          width="110"
          label="总的手续费"
        />
        <el-table-column prop="bankNo" label="原因">
          <template #default="scope">
            <el-button
              link
              type="text"
              size="small"
              @click="reasonClick(scope.row)"
            >
              {{ scope.row.state === 5 ? "查看原因" : null }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          :formatter="judgeState"
          width="100"
          label="提现状态"
        />
        <el-table-column fixed="right" width="80" label="操作">
          <template v-slot:default="scope">
            <div
              class="div-cell"
              v-if="scope.row.state === 3 && pinia.isShow[89]"
            >
              <el-button
                link
                type="primary"
                size="small"
                @click="withdrawalDialog(scope.row)"
              >
                {{ "审核" }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <el-dialog
      title="提现失败原因"
      v-model="dialogVisible"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>{{ checkReason }}</span>
    </el-dialog>

    <!-- 提现审核dialog -->
    <div>
      <el-dialog
        v-model="withdrawalDialogVisible"
        title="提现审核"
        center="true"
        modal="true"
        width="450px"
      >
        <el-form :model="withdrawalParam">
          <el-form-item label="提现金额:">{{
            withdrawalParam.price
          }}</el-form-item>
          <el-form-item label="审核类型:">
            <el-radio-group
              v-model="withdrawalParam.result"
              @change="resultChange"
            >
              <el-radio :label="4">审核通过</el-radio>
              <el-radio :label="5">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="不通过原因">
            <el-input
              v-model.trim="withdrawalParam.reason"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :disabled="withdrawalReason"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="withdrawalDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              color="#ea5b24"
              @click="withdrawalReview()"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import {
  findWithdrawalOrderApi,
  findWithdrawalExcelApi,
  withdrawalReviewApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
// 汇总数据
const summaryData: any = reactive({
  checkAmt: null, //提现审核中总金额
  failAmt: null, //提现失败
  handleAmt: null, //	提现处理中中总金额
  successAmt: null, ////提现成功总金额
});

const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 提现审核dialog控制
const withdrawalDialogVisible = ref(false);
// 不通过原因禁用
const withdrawalReason = ref(true);
// 提现审核参数
const withdrawalParam = reactive({
  price: null,
  orderId: null,
  result: null,
  reason: null,
});

const dialogVisible = ref(false);
const checkReason = ref("");

const reasonClick = (row) => {
  checkReason.value = row.checkReason;
  dialogVisible.value = true;
};

// 审核dialog
const withdrawalDialog = (row) => {
  withdrawalDialogVisible.value = true;
  withdrawalParam.orderId = row.orderId;
  withdrawalParam.price = row.price;

  withdrawalParam.result = 4;
  withdrawalReason.value = true;
  withdrawalParam.reason = null;
};

const resultChange = (val) => {
  switch (val) {
    case 4:
      withdrawalParam.reason = null;
      withdrawalReason.value = true;
      break;
    case 5:
      withdrawalReason.value = false;
      break;
  }
};

//获取选中时间
let curDate = null;
const calendar = (val) => {
  curDate = val[0].getTime();
};

// //日期选择区间
const disabledDateFn = (time: any) => {
  let three = 90 * 24 * 3600 * 1000;
  let minTime = curDate - three;
  let maxTime = curDate + three;
  return curDate != null
    ? time.getTime() > maxTime || time.getTime() < minTime
    : false;
};

// 判断状态显示
const judgeState = (row) => {
  switch (row.state) {
    case 0:
      return "处理中";
    case 1:
      return "提现成功";
    case 2:
      return "提现失败";
    case 3:
      return "审核中";
    case 4:
      return "审核通过";
    case 5:
      return "审核不通过";
    default:
      return "错误";
  }
};

// 搜索模型
const searchModel: any = reactive({
  dealNo: null,
  orderNo: null,
  state: null,
  userId: null,
  withdrawType: null,
  createDate: null,
  startTime: null,
  endTime: null,
  checkTime: null,
  checkStartTime: null,
  checkEndTime: null,
  withdrawTime: null,
  withdrawStartTime: null,
  withdrawEndTime: null,
  packSeriesName: null,

  pageNum: page,
  pageSize: size,
});

// 翻页
let flipData = reactive({
  pageNum: page,
  pageSize: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.pageNum = page.value;
  findOrder(flipData);
};

// 搜索提现订单
const searchOrder = () => {
  page.value = 1;
  if (searchModel.createDate) {
    searchModel.startTime = formatDateTime(searchModel.createDate[0]);
    searchModel.endTime = formatDateTime(searchModel.createDate[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.startTime = null;
    searchModel.endTime = null;
  }
  if (searchModel.checkTime) {
    searchModel.checkStartTime = formatDateTime(searchModel.checkTime[0]);
    searchModel.checkEndTime = formatDateTime(searchModel.checkTime[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.checkStartTime = null;
    searchModel.checkEndTime = null;
  }
  if (searchModel.withdrawTime) {
    searchModel.withdrawStartTime = formatDateTime(searchModel.withdrawTime[0]);
    searchModel.withdrawEndTime = formatDateTime(
      searchModel.withdrawTime[1]
    ).replace("00:00:00", "23:59:59");
  } else {
    searchModel.withdrawStartTime = null;
    searchModel.withdrawEndTime = null;
  }
  searchParmSearch();
  findOrder(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

const processingTime = (startTime, endTime) => {
  if (startTime == endTime) {
    return endTime.replace("00:00:00", "23:59:59");
  } else {
    return endTime;
  }
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

// 查询提现订单
const findOrder = (searchModel) => {
  findWithdrawalOrderApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.pages.items;
      totalNum.value = res.data.data.pages.total;

      summaryData.checkAmt = res.data.data.checkAmt ?? 0;
      summaryData.failAmt = res.data.data.failAmt ?? 0;
      summaryData.handleAmt = res.data.data.handleAmt ?? 0;
      summaryData.successAmt = res.data.data.successAmt ?? 0;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 提现审核
const withdrawalReview = () => {
  if (
    withdrawalParam.result == 5 &&
    (withdrawalParam.reason == "" || withdrawalParam.reason == null)
  ) {
    ElMessage.error("请输入不通过原因.");
  } else {
    withdrawalReviewApi(withdrawalParam).then((res) => {
      if (res.data.code === 2000) {
        ElMessage({
          message: "审核成功.",
          type: "success",
        });
      } else {
        ElMessage.error(
          "审核失败:" + res.data.msg.slice(res.data.msg.indexOf("err:") + 4)
        );
      }
      withdrawalDialogVisible.value = false;
      findOrder(searchModel);
    });
  }
};

//导出订单
const exportOrder = () => {
  findWithdrawalExcelApi(searchModel).then((res) => {
    const blob = new Blob([res.data]);
    const fileName = "提现订单数据.xls";
    const elink = document.createElement("a"); // 创建a标签
    elink.download = fileName; // 为a标签添加download属性
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click(); // 点击下载
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink); // 释放标签
  });
};

onMounted(() => {
  findOrder(searchModel);

  var today = new Date(); //当天
  today.setMonth(today.getMonth() - 3); //三个月前，时间戳
  today.toLocaleDateString(); //格式化时间
  searchModel.createDate = [today, new Date()];
});
</script>

<style scoped>
:deep(.demo-form-inline) {
  display: grid;
  justify-items: stretch;
  grid-template-columns: repeat(auto-fill, 25%);
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item) {
  width: 90%;
}

.subBtnBox {
  width: 100%;
  margin-bottom: 20px;
  display: block;
  text-align: center;
}

.div-summaryData {
  background-color: rgb(187, 190, 195);
  height: 34px;
  margin-top: 20px;
  line-height: 33px;
}

.text-summaryData {
  color: black;
  font-size: 14px;
  margin-right: 30px;
  margin-left: 10px;
}
</style>
